const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const pool = require('../config/db');

console.log('auth 路由模块加载成功');
router.post('/register', async (req, res) => {
  try {
    const { userId, username, password } = req.body;

    const [existingUsers] = await pool.execute(
      'SELECT * FROM user WHERE id = ?',
      [userId]
    );

    if (existingUsers.length > 0) {
      return res.status(400).json({ message: '用户ID已存在' });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    await pool.execute(
      'INSERT INTO user (id, username, password, role) VALUES (?, ?, ?, 0)',
      [userId, username, hashedPassword]
    );

    res.status(201).json({ message: '注册成功' });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '注册失败' });
  }
});

router.post('/login', async (req, res) => {
  try {
    const { userId, password } = req.body;
    
    const [users] = await pool.execute(
      'SELECT * FROM user WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      return res.status(401).json({ message: '用户ID或密码错误' });
    }

    const user = users[0];
    const isValidPassword = await bcrypt.compare(password, user.password);
    
    if (!isValidPassword) {
      return res.status(401).json({ message: '用户ID或密码错误' });
    }

    const token = jwt.sign(
      { 
        userId: user.id,
        username: user.username,
        role: user.role 
      },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        role: user.role
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '登录失败' });
  }
});


module.exports = router; 